package area

import (
	"context"
	"encoding/json"
	"errors"
	"git.mycaigou.com/gfyx/common/rpc_client"
	"git.mycaigou.com/gfyx/micro-gfyx-api/infrastructure/common/constants"
	pb "git.mycaigou.com/gfyx/micro-gfyx-api/proto/micro_gfyx_oppty_service_proto/micro-gfyx-oppty-service/base"
)

type areaRepository struct {
}

// NewAreaRepository 构造函数
func NewAreaRepository() AreaRepositoryIface {
	return &areaRepository{}
}

// AreaTrees 区域列表
func (r *areaRepository) AreaTrees(ctx context.Context) ([]map[string]interface{}, error) {
	conn, ctx, err := rpc_client.GetClientConn(ctx, constants.MICRO_GFYX_OPPTY_SERVICE)
	if err != nil {
		return nil, err
	}
	defer func() {
		_ = conn.Close()
	}()
	client := pb.NewBaseAreaServiceClient(conn)
	resp, err := client.AreaTrees(ctx, &pb.AreaTreesRequest{})
	if err != nil {
		return nil, err
	}

	if resp == nil {
		return nil, errors.New("获取地区信息失败")
	}

	jsonMap := make([]map[string]interface{}, 0)
	err = json.Unmarshal([]byte(resp.AreaJsonStr), &jsonMap)
	if err != nil {
		return nil, err
	}

	return jsonMap, nil
}
